<template>
  <div class="athlete_team">
    <div class="entry_check_wrap gl_clear">
      <van-button :loading="checkEntryLoading" type="info" size="small" block @click="clickChooseAthleteForTeam">选择运动员，获取项目</van-button>
      <div class="individual_check_wrap gl_fl" @click="onChangeMemberRadio">
        <span class="gl_mr_10">{{ checkedMember.name }}</span>
        <span class="gl_mr_10">{{ dictGenderMap[checkedMember.genderCode] ? dictGenderMap[checkedMember.genderCode].value : '' }}</span>
        <span>{{ checkedMember.birthDate ? checkedMember.birthDate.slice(0, 10) : '' }}</span>
      </div>
    </div>

    <!-- 报项列表 -->
    <div v-if="entryList.length" class="individual_list_wrap">
      <van-loading v-if="entryListLoading" class="loadingStyle" />

      <div v-if="gameInfo.isFinal && substationList.length" class="event_group">
        <div class="event_title">赛区选择</div>
        <div class="event_list">
          <van-radio-group v-model="activeSubstation">
            <van-radio v-for="(item, index) in substationList" :key="index" class="event_item" :name="item.id">{{ item.competitionName }}</van-radio>
          </van-radio-group>
        </div>
      </div>

      <div v-for="(item, index) in entryShowList" :key="index" class="event_group">
        <div class="event_title">{{ item.name }}</div>
        <div class="event_list">
          <van-checkbox-group v-model="entryCheckGroupData[item.categoryId]" :max="item.maxEntry">
            <template v-for="(jtem, jndex) in item.children">
              <van-checkbox v-if="jtem.eventRegTypeCode === 'I'" :key="jndex" class="event_item" shape="square" icon-size="16px" :label="jtem" :name="jtem" border>
                <span class="gl_mr_5" :class="computeNeedDisable(item, jtem) ? 'disable_checkItem' : ''">
                  {{ jtem.eventGroupName }}{{ jtem.eventShortName }}
                </span>
                <!-- <div style="width:160px;">
                  <van-field
                    v-if="jtem.eventRegTypeCode !== 'I'"
                    label="分组："
                    label-width="50px"
                    readonly
                    clickable
                    :value="jtem.athleteEntriedTeamNo ? jtem.athleteEntriedTeamNo + '组' : ''"
                    placeholder="点击选择分组"
                    @click.native.stop.prevent="clickChooseTeamNo(jtem)"
                  />
                </div> -->
              </van-checkbox>
              <div
                v-if="jtem.eventRegTypeCode !== 'I'"
                :key="jndex"
                class="mock_checkbox_wrap"
                :class="{
                  'checked': jtem.athleteHasEntried,
                  'disabled': (item.hasEntry >= item.maxEntry) && !jtem.athleteHasEntried
                }"
                @click="chooseTeamMember(jtem, (item.hasEntry >= item.maxEntry) && !jtem.athleteHasEntried)"
              >
                <span class="mock_checkbox gl_mr_10">
                  <van-icon name="success" color="#fff" />
                </span>
                <span>
                  <span class="gl_mr_10">{{ jtem.eventGroupName }}{{ jtem.eventShortName }}</span>
                  <van-icon style="vertical-align: middle;" :color="(item.hasEntry >= item.maxEntry) && !jtem.athleteHasEntried ? '#c9c9c9' : '#6f6f6f'" name="friends" />
                </span>
              </div>
            </template>
          </van-checkbox-group>
        </div>
      </div>

      <TeamCompetition
        ref="refTeamCompetitionMember"
        :title="teamCompetitionTitle"
        :gameInfo = 'gameInfo'
        :require-member="mainMember"
        :team-entry="teamCompetitionTeamEntry"
        :option-member="teamCompetitionLeftList"
        :max-select-member-num="teamCompetitionMaxCount"
        :min-select-member-num="teamCompetitionMinCount"
        :select-member="teamCompetitionRightList"
        @onTeamCompetitionSubmit="onTeamCompetitionSubmit"
        @onDeleteGroupMember="onDeleteGroupMember('TeamCompetition')"
      />

      <!-- 新版本成员选择 -->
      <TeamNoneCompetition
        ref="refTeamNoneCompetitionMember"
        :title="teamNoneCompetitionTitle"
        :gameInfo = 'gameInfo'
        :require-member="mainMember"
        :team-entry="teamNoneCompetitionTeamEntry"
        :option-member="teamNoneCompetitionLeftList"
        :max-select-member-num="teamNoneCompetitionMaxCount"
        :min-select-member-num="teamNoneCompetitionMinCount"
        :select-member="teamNoneCompetitionRightList"
        @onTeamNoneCompetitionSubmit="onTeamNoneCompetitionSubmit"
        @onDeleteGroupMember="onDeleteGroupMember('TeamNoneCompetition')"
      />

      <!-- 老版本组号选择 -->
      <van-action-sheet v-model="showActionSheet" :actions="actionsList" cancel-text="取消" close-on-click-action @select="onSelectActionSheet" />
    </div>
    <div v-else class="individual_list_noData">
      <p>请检测并获取项目</p>
    </div>

    <!-- 步骤控制按钮 -->
    <van-row :gutter="10" class="bottom_btn_position">
      <van-col span="8" align="center">
        <van-button type="default" block @click="clickPrevStep()">上一步</van-button>
      </van-col>
      <van-col span="8" align="center">
        <van-button type="info" block :loading="submitLoading" @click="clickSubmit()">提交报名</van-button>
      </van-col>
      <van-col span="8" align="center">
        <van-button type="info" block @click="clickGoConfirmEntry()">已报项目</van-button>
      </van-col>
    </van-row>
  </div>
</template>

<script>
import {
  api_POST_EventsManagementEntryQueryEventsToEntryForRegisters, // 1-获取已存在人员可报的赛事项目列表
  api_GET_EventsManagementEntryTeamEntry, // 获取团体报项
  api_GET_EventsManagementEntryTeamEntryMemberCandidates, // 获取团体报项候选人员列表
  api_POST_EventsManagementEntrySaveTeamEntry, // 保存团体报项
  api_DELETE_EventsManagementEntryTeamEntry, // 删除团体报项
  api_POST_EventsManagementEntryQuerySubCompetitionsToEntryForRegisters // 0-获取已存在人员联赛决赛代表的分站赛赛事列表
} from '@/extend/api/gameswaggerApi/app';

import {
  SiSTKWEventsManagementGetEntryEventsInput // 1-获取已存在人员可报的赛事项目列表
} from '@/lib/form/game/swaggerForm';

import TeamCompetition from '../../components/TeamCompetition';
import TeamNoneCompetition from '../../components/TeamNoneCompetition';

export default {
  components: {
    TeamCompetition,
    TeamNoneCompetition
  },
  props: {
    submitLoading: {
      type: Boolean,
      default: false
    },
    // 报名人员列表
    players: {
      type: Array,
      default () {
        return [];
      }
    },
    userInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    gameInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    requiredIdData: {
      type: Object,
      default () {
        return {};
      }
    },
    dict: {
      type: Object,
      default () {
        return {};
      }
    }
  },
  data () {
    return {
      activeSubstation: '',
      substationList: [],
      // 选择报名的人
      checkedMember: {},
      entryVO: new SiSTKWEventsManagementGetEntryEventsInput(), // 1-获取已存在人员可报的赛事项目列表
      entryList: [],
      entryShowList: [],
      entryCheckGroupData: {},
      checkEntryLoading: false,
      currentEntry: null, // 当前选中的报项
      showActionSheet: false, // 是否显示动作面板，来选择分组
      actionsList: [], // 每次点击处理的数据
      entryListLoading: false,

      mainMember: {},

      teamCompetitionTitle: '',
      teamCompetitionLeftList: [],
      teamCompetitionRightList: [],
      teamCompetitionMaxCount: 0,
      teamCompetitionMinCount: 0,
      teamCompetitionCurrent: {}, // 当前选中的团体竞技项目
      teamCompetitionTeamEntry: {}, // 获取到的团体报项数据

      teamNoneCompetitionTitle: '',
      teamNoneCompetitionLeftList: [],
      teamNoneCompetitionRightList: [],
      teamNoneCompetitionMaxCount: 0,
      teamNoneCompetitionMinCount: 0,
      teamNoneCompetitionCurrent: {}, // 当前选中的普通团体项目
      teamNoneCompetitionTeamEntry: {} // 获取到的团体报项数据
    };
  },
  computed: {
    dictGenderMap() {
      const _map = {};
      this.dict.gender.forEach(item => {
        _map[item.code] = item;
      });
      return _map;
    }
  },
  watch: {
    userInfo: {
      deep: true,
      handler() {
        this.resetViewData();
      }
    },
    checkedMember: {
      deep: true,
      handler(val) {
        this.entryList = [];
        this.entryCheckGroupData = {};
        this.mainMember = val;
        if (val.id) {
          // this.checkEntry();
          this.onChangeMemberRadio();
        }
      }
    },
    players: {
      deep: true,
      handler(val) {
        if (val.length) {
          this.checkedMember = val[0];
        }
      }
    }
  },
  methods: {
    // 团体非竞技成员选择
    entryTeamNoneCompetitionMember(data) {
      this.teamNoneCompetitionCurrent = data;
      this.entryListLoading = true;
      this.teamNoneCompetitionTitle = data.eventLongName;
      this.teamNoneCompetitionMaxCount = data.maxTeamMembersCount;
      this.teamNoneCompetitionMinCount = data.minTeamMembersCount;

      const _promiseEntry = this.getTeamEntry({
        EventId: data.id,
        RegisterId: this.checkedMember.id,
        DelegationId: this.requiredIdData.delegationId
      });

      const _promiseEntryMember = this.getTeamEntryMemberCandidates({
        EventId: data.id,
        DelegationId: this.requiredIdData.delegationId
      });

      Promise.all([_promiseEntry, _promiseEntryMember])
        .then(
          res => {
            this.entryListLoading = false;
            const teamEntryRes = res[0];
            const teamEntryMemberCandidatesRes = res[1];
            this.teamNoneCompetitionTeamEntry = teamEntryRes;
            this.teamNoneCompetitionTitle = `${this.teamNoneCompetitionTitle} ${teamEntryRes.teamNo}组`;
            this.teamNoneCompetitionLeftList = teamEntryMemberCandidatesRes;
            this.teamNoneCompetitionRightList = teamEntryRes.members;
            this.$refs.refTeamNoneCompetitionMember.open();
          }
        )
        .catch(
          error => {
            this.entryListLoading = false;
            console.log('error: ', error);
          }
        );
    },
    // 团体竞技成员选择
    entryTeamCompetitionMember(data) {
      this.teamCompetitionCurrent = data;
      this.entryListLoading = true;
      this.teamCompetitionTitle = data.eventLongName;
      this.teamCompetitionMaxCount = data.maxTeamMembersCount;
      this.teamCompetitionMinCount = data.minTeamMembersCount;

      const _promiseEntry = this.getTeamEntry({
        EventId: data.id,
        RegisterId: this.checkedMember.id,
        DelegationId: this.requiredIdData.delegationId
      });

      const _promiseEntryMember = this.getTeamEntryMemberCandidates({
        EventId: data.id,
        DelegationId: this.requiredIdData.delegationId
      });

      Promise.all([_promiseEntry, _promiseEntryMember])
        .then(
          res => {
            this.entryListLoading = false;
            const teamEntryRes = res[0];
            const teamEntryMemberCandidatesRes = res[1];
            this.teamCompetitionTeamEntry = teamEntryRes;
            this.teamCompetitionTitle = `${this.teamCompetitionTitle} ${teamEntryRes.teamNo}组`;
            this.teamCompetitionLeftList = teamEntryMemberCandidatesRes;
            this.teamCompetitionRightList = this.formatWeightClasses(data, teamEntryRes.members);
            this.$refs.refTeamCompetitionMember.open();
          }
        )
        .catch(
          error => {
            this.entryListLoading = false;
            console.log('error: ', error);
          }
        );
    },
    formatWeightClasses (data, members) {
      members = members || [];
      const _rightList = JSON.parse(JSON.stringify(data.weightClasses));

      for (let i = 0; i < _rightList.length; i++) {
        const item = _rightList[i];
        item._children = members.filter(jtem => jtem.eventWeightClassId === item.id);
      }
      console.log('data, members: ', data, members);
      return _rightList;
    },
    onDeleteGroupMember (type) {
      // 团体竞技
      if (type === 'TeamCompetition') {
        this.deleteGroupMemberApi({
          EntryId: this.teamCompetitionTeamEntry.teamEntryId,
          DelegationId: this.requiredIdData.delegationId,
          EventId: this.teamCompetitionCurrent.id
        }, 'refTeamCompetitionMember');
      }
      // 团体
      if (type === 'TeamNoneCompetition') {
        this.deleteGroupMemberApi({
          EntryId: this.teamNoneCompetitionTeamEntry.teamEntryId,
          DelegationId: this.requiredIdData.delegationId,
          EventId: this.teamNoneCompetitionCurrent.id
        }, 'refTeamNoneCompetitionMember');
      }
    },
    // 删除整组成员
    deleteGroupMemberApi (vo, refName) {
      api_DELETE_EventsManagementEntryTeamEntry(vo)
        .then(
          res => {
            this.$emit('onReGetByPerson'); // 重新请求byperson接口

            // 当提交团体竞技或混合团体竞技后
            if (refName === 'refTeamCompetitionMember') {
              this.teamCompetitionCurrent.athleteHasEntried = false;
              const _categoryId = this.teamCompetitionCurrent.$categoryId;

              // 如果 entryCheckGroupData 中没有则要push,有则不需要
              const _findCurrIndex = this.entryCheckGroupData[_categoryId].findIndex(item => item.id === this.teamCompetitionCurrent.id);
              if (_findCurrIndex !== -1) {
                this.changeEntryShowListHasEntry(_categoryId, 'sub');
                this.entryCheckGroupData[_categoryId].splice(_findCurrIndex, 1);
              }
            }

            // 当提交普通团体后
            if (refName === 'refTeamNoneCompetitionMember') {
              this.teamNoneCompetitionCurrent.athleteHasEntried = false;
              const _categoryId = this.teamNoneCompetitionCurrent.$categoryId;

              // 如果 entryCheckGroupData 中没有则要push,有则不需要
              const _findCurrIndex = this.entryCheckGroupData[_categoryId].findIndex(item => item.id === this.teamNoneCompetitionCurrent.id);
              if (_findCurrIndex !== -1) {
                this.changeEntryShowListHasEntry(_categoryId, 'sub');
                this.entryCheckGroupData[_categoryId].splice(_findCurrIndex, 1);
              }
            }

            // this.checkEntry(); // 重新检测报项信息
            this.$refs[refName].close(); // 关闭弹窗
            this.$toast.success(`删除团体报项成功`);
          }
        )
        .catch(
          error => {
            this.$refs[refName].hideLoading();
            this.$toast.fail(`删除团体报项失败 ${error.error.message || ''}`);
          }
        );
    },
    // 选择团体成员 非重竞技
    chooseTeamMember (data, isDisabled) {
      if (!isDisabled) {
        if (data.preEventTypeCode === 'CompetitiveTeam' || data.preEventTypeCode === 'MixedCompetitiveTeam') {
          this.entryTeamCompetitionMember(data);
        } else {
          this.entryTeamNoneCompetitionMember(data);
        }
      } else {
        console.log('chooseTeamMember', isDisabled);
      }
    },
    // 获取团体报项候选人员列表
    getTeamEntryMemberCandidates (qo) {
      return new Promise((reslove, reject) => {
        api_GET_EventsManagementEntryTeamEntryMemberCandidates(qo)
          .then(
            res => {
              reslove(res);
            }
          )
          .catch(
            error => {
              this.$toast.fail(`获取团体报项候选人员列表失败 ${error.error.message || ''}`);
              reject(error);
            }
          );
      });
    },
    // 获取团体报项API
    getTeamEntry(qo) {
      return new Promise((reslove, reject) => {
        api_GET_EventsManagementEntryTeamEntry(qo)
          .then(
            res => {
              reslove(res);
            }
          )
          .catch(
            error => {
              reject(error);
              this.$toast.fail(`获取团体报项失败 ${error.error.message || ''}`);
            }
          );
      });
    },
    // 团体竞技报名
    onTeamCompetitionSubmit (data) {
      const _ids = data.map(item => {
        return {
          registerIds: item._children.map(jtem => jtem.registerId || jtem.id)
        };
      });
      this.submitTeamEntry({
        eventId: this.teamCompetitionCurrent.id,
        delegationId: this.requiredIdData.delegationId,
        entryId: this.teamCompetitionTeamEntry.teamEntryId || '',
        teamNo: this.teamCompetitionTeamEntry.teamNo,
        weightClasses: _ids
      }, 'TeamCompetition');
    },
    // 团体非竞技确认报名
    onTeamNoneCompetitionSubmit (data) {
      const _ids = data.map(item => item.registerId || item.id);
      this.submitTeamEntry({
        eventId: this.teamNoneCompetitionCurrent.id,
        delegationId: this.requiredIdData.delegationId,
        entryId: this.teamNoneCompetitionTeamEntry.teamEntryId || '',
        teamNo: this.teamNoneCompetitionTeamEntry.teamNo,
        weightClasses: [{ registerIds: _ids }]
      }, 'TeamNoneCompetition');
    },
    // 获取已存在人员联赛决赛代表的分站赛赛事列表
    getSubstationList (vo) {
      api_POST_EventsManagementEntryQuerySubCompetitionsToEntryForRegisters(vo)
        .then(
          res => {
            this.substationList = res || [];
            const _findResult = res.find(item => item.hasUsed);
            this.activeSubstation = _findResult ? _findResult.id : '';
          }
        )
        .catch(
          error => {
            this.$toast({ type: 'fail', message: `获取分站列表失败 ${error.error.message}` });
          }
        );
    },
    // 获取报项，如果是联赛中的决赛则需要获取赛区列表
    onChangeMemberRadio () {
      if (this.gameInfo.isFinal) {
        this.getSubstationList({
          competitionId: this.gameInfo.id,
          registerId: this.checkedMember.id,
          delegationId: this.requiredIdData.delegationId,
          hasEntriedEvent: true
        });
      }
      this.checkEntry();
    },
    // 保存团体报项API
    submitTeamEntry(vo, type) {
      api_POST_EventsManagementEntrySaveTeamEntry(vo)
        .then(
          res => {
            // this.checkEntry(() => {
            //   // 静默提交一次报名,此方式已废弃
            //   this.clickSubmit(true);
            // });

            // this.$emit('onReGetByPerson'); // 重新获取byperson

            // 当提交团体竞技或混合团体竞技后
            if (type === 'TeamCompetition') {
              this.teamCompetitionCurrent.athleteHasEntried = true;
              const categoryId = this.teamCompetitionCurrent.eventCategoryId;
              if (this.entryCheckGroupData[categoryId]) {
                this.changeEntryShowListHasEntry(categoryId, 'add');
                this.teamCompetitionCurrent.athleteEntriedTeamNo = res.teamNo;
                // 如果 entryCheckGroupData 中没有则要push,有则不需要
                const _findCurr = this.entryCheckGroupData[categoryId].find(item => item.id === this.teamCompetitionCurrent.id);
                if (!_findCurr) {
                  this.entryCheckGroupData[categoryId].push(this.teamCompetitionCurrent);
                }
              }
              this.$refs.refTeamCompetitionMember.close();
            }

            // 当提交普通团体后
            if (type === 'TeamNoneCompetition') {
              this.teamNoneCompetitionCurrent.athleteHasEntried = true;
              const categoryId = this.teamNoneCompetitionCurrent.eventCategoryId;
              if (this.entryCheckGroupData[categoryId]) {
                this.changeEntryShowListHasEntry(categoryId, 'add');
                this.teamNoneCompetitionCurrent.athleteEntriedTeamNo = res.teamNo;
                // 如果 entryCheckGroupData 中没有则要push,有则不需要
                const _findCurr = this.entryCheckGroupData[categoryId].find(item => item.id === this.teamNoneCompetitionCurrent.id);
                if (!_findCurr) {
                  this.entryCheckGroupData[categoryId].push(this.teamNoneCompetitionCurrent);
                }
              }
              this.$refs.refTeamNoneCompetitionMember.close();
            }
            // 不给用户成功提示，目的是让用户以为报名还未完成，诱导点击提交报名按钮，触发提交教练领队信息
            // this.$toast.success(`保存团体报项成功`);
          }
        )
        .catch(
          error => {
            if (type === 'TeamCompetition') {
              this.$refs.refTeamCompetitionMember.hideLoading();
            }
            if (type === 'TeamNoneCompetition') {
              this.$refs.refTeamNoneCompetitionMember.hideLoading();
            }
            this.$toast.fail(`保存团体报项失败 ${error.error.message || ''}`);
          }
        );
    },
    // 改变HasEntry 的值，处理复选禁用
    changeEntryShowListHasEntry (categoryId, type) {
      const _findIndex = this.entryShowList.findIndex(item => item.categoryId === categoryId);
      if (_findIndex !== -1) {
        let _num = this.entryShowList[_findIndex].hasEntry;
        if (type === 'add') {
          _num++;
        }
        if (type === 'sub') {
          _num--;
        }
        this.$set(this.entryShowList[_findIndex], 'hasEntry', _num);
      }
    },
    // ---
    clickChooseTeamNo (data) {
      this.showActionSheet = true;
      this.currentEntry = data;
      const _teamList = [];
      for (let i = 1; i <= data.$eventMaxTeamNo; i++) {
        _teamList.push({
          name: i + '组',
          value: i
        });
      }
      this.actionsList = _teamList;
    },
    onSelectActionSheet (item) {
      this.currentEntry.athleteEntriedTeamNo = item.value;
    },
    // 点击执行上一步操作
    clickPrevStep () {
      this.$emit('onPrevStep');
    },
    // 点击提交报名
    clickSubmit () {
      // 校验运动员是否选择
      if (!this.checkedMember.id) {
        this.$toast.fail(`请选择参赛运动员`);
        return;
      }

      // 校验是否选择报项
      let _entryCheckList = [];
      for (const k in this.entryCheckGroupData) {
        const ktem = this.entryCheckGroupData[k];
        _entryCheckList = _entryCheckList.concat(ktem);
      }
      if (!_entryCheckList.length) {
        this.$toast.fail(`请选择要报名的项目`);
        return;
      }

      // 处理报项数据，准备报名
      const _allEventList = [];

      for (let i = 0; i < _entryCheckList.length; i++) {
        const item = _entryCheckList[i];
        console.log('clickSubmit -> item', item);
        if (item.eventRegTypeCode === 'I') {
          // 个人项目
          _allEventList.push({
            eventId: item.id
          });
        } else {
          // 团体项目，判断是否选择了分组
          if (item.athleteEntriedTeamNo) {
            _allEventList.push({
              eventId: item.id,
              teamNo: item.athleteEntriedTeamNo,
              teamName: item.athleteEntriedTeamNo + '组'
            });
          } else {
            this.$toast.fail(`${item.eventLongName} 未选择分组`);
            return false;
          }
        }
      }

      const _eventData = {
        entrySubstationId: this.activeSubstation,
        _allEventList: _allEventList
      };

      this.$emit('onSubmitTeamEntry', this.checkedMember.id, _eventData);
    },
    // 重置页面为初始值显示
    resetViewData() {
      this.substationList = [];
      this.entryShowList = [];
    },
    // 提交报名
    clickGoConfirmEntry () {
      // this.resetViewData();
      this.$emit('goConfirmEntry');
    },
    // 检测报项信息
    checkEntry () {
      if (!this.checkedMember.id) {
        this.$toast.fail(`请选择一名参赛运动员`);
        return;
      }
      this.entryVO.competitionId = this.gameInfo.id;
      this.entryVO.registerId = this.checkedMember.id;
      this.entryVO.delegationId = this.requiredIdData.delegationId;
      this.entryVO.hasEntriedEvent = true;
      this.checkEntryLoading = true;
      api_POST_EventsManagementEntryQueryEventsToEntryForRegisters(this.entryVO)
        .then(
          res => {
            if (res.length) {
              this.entryList = res;
              this.entryCheckGroupData = {};
              this.entryShowList = this.formatEntryShowData(res);
              // this.$toast.success(`报项检测成功`);
            } else {
              this.$toast.fail(`没有检测到可以报名的项目`);
            }
            this.checkEntryLoading = false;
          }
        )
        .catch(
          error => {
            this.$toast.fail(`获取人员可报的赛事项目列表失败 ${error.error.message || ''}`);
            this.checkEntryLoading = false;
          }
        );
    },
    // 处理报项显示数据
    formatEntryShowData (list) {
      const _returnData = {};
      for (let i = 0; i < list.length; i++) {
        const item = list[i];
        item.$categoryId = item.eventCategoryId;
        item.$eventMaxTeamNo = item.eventMaxTeamNo ? item.eventMaxTeamNo : 20;
        if (_returnData[item.$categoryId]) {
          _returnData[item.$categoryId].children.push(item);
        } else {
          _returnData[item.$categoryId] = {
            categoryId: item.$categoryId,
            name: item.eventCategoryName,
            maxEntry: item.categoryMaxEntry,
            children: [item]
          };
          // 处理复选框数据
          this.formatEntryShowDataCheckbox(item.$categoryId);
        }
        // 报了这个项目
        if (item.athleteHasEntried) {
          this.entryCheckGroupData[item.$categoryId].push(item);
        }
      }

      // 排序
      for (const k in _returnData) {
        const ktem = _returnData[k];
        let hasEntry = 0;
        ktem.children.forEach(item => {
          if (item.athleteHasEntried) {
            hasEntry++;
          }
        });
        ktem.hasEntry = hasEntry;
        ktem.children.sort((a, b) => a.eventShortName - b.eventShortName);
      }

      const _returnList = Object.values(_returnData);
      _returnList.sort((a, b) => new Date(a.categoryCreateTime) - new Date(b.categoryCreateTime));
      return _returnList;
    },
    // 处理报项显示数据的复选框
    formatEntryShowDataCheckbox (categoryId) {
      if (categoryId in this.entryCheckGroupData) {
        return;
      }
      this.$set(this.entryCheckGroupData, categoryId, []);
    },
    chooseAthleteAndGetEntry (athlete) {
      // 供外部调用
      console.log('chooseAthleteAndGetEntry -> athlete', athlete);
      this.checkedMember = athlete;
      this.onChangeMemberRadio();
    },
    clickChooseAthleteForTeam () {
      this.$emit('onChooseAthleteForTeam');
    },
    computeNeedDisable (itemData, jtemData) {
      const _len = this.entryCheckGroupData[itemData.categoryId].length;
      const _maxEntry = itemData.maxEntry;
      // 是否被勾选
      let isSelect = false;
      if (_len) {
        const _findData = this.entryCheckGroupData[itemData.categoryId].find(item => item === jtemData);
        if (_findData) {
          isSelect = true;
        }
      }
      return _len >= _maxEntry && !isSelect;
    }
  }
};
</script>

<style lang="scss" scoped>
.athlete_team .van-cell {
  padding: 0;
}

.entry_check_wrap {
  background: #ffffff;
  border-radius: 10px;
  box-shadow: 0px 0px 10px 0px rgba(0,0,0,0.10);
  margin-bottom: 20px;
  overflow: hidden;
}
.individual_check_wrap {
  box-sizing: border-box;
  width: 100%;
  height: 30px;
  text-align: center;
  line-height: 28px;
  font-size: 14px;
  color: #353434;
}

.event_group {
  margin-bottom: 24px;
}
.event_item {
  margin-bottom: 20px;
}
.tip_noData {
  text-align: center;
  line-height: 60px;
  color: #c1c1c1
}
.individual_list_wrap {
  position: relative;
  padding: 10px 0;
  min-height: 360px;
  box-sizing: border-box;
}
.event_group {
  margin-bottom: 20px;
}
.event_title {
  position: relative;
  height: 20px;
  font-size: 16px;
  line-height: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}
.event_list {
  padding: 10px 20px;
  padding-left: 20px;
  background: #ffffff;
  border-radius: 5px;
  box-shadow: 0 0 5px 0 rgba(0,0,0,0.10);
}
.event_item {
  font-size: 14px;
  margin-bottom: 10px;
}
.event_item:last-child {
  margin-bottom: 0;
}
.individual_list_noData {
  padding: 140px 0px 215px;
  text-align: center;
  font-size: 16px;
  color: #c1c1c1;
}

.disable_checkItem {
  color: #c9c9c9;
}

.mock_checkbox_wrap {
  display: flex;
  align-items: center;
  min-height: 20px;
  word-break: break-all;
  margin-bottom: 10px;
  line-height: 20px;
  font-size: 14px;
  color: #323233;
}
.mock_checkbox_wrap span {
  vertical-align: middle;
}
.mock_checkbox_wrap.checked {
  border-color: #1989fa;
  color: #1989fa;
}
.mock_checkbox_wrap.disabled {
  border-color: #e6ebf5;
  color: #c9c9c9;
}
.mock_checkbox {
  display: inline-block;
  box-sizing: border-box;
  width: 16px;
  height: 16px;
  background-color: #FFFFFF;
  border: 1px solid #c8c9cc;
}
.mock_checkbox_wrap.checked .mock_checkbox {
  position: relative;
  background-color: #1989fa;
  border-color: #1989fa;
}
// .mock_checkbox_wrap.disabled .mock_checkbox {
//   position: relative;
//   background-color: #edf2fc;
//   border-color: #dcdfe6;
// }

.loadingStyle {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  z-index: 11;
  background-color: rgba(255, 255, 255, 0.7);
  text-align: center;
}
</style>
